package com.huahua.api.controller;

import com.huahua.api.entity.base.R;
import com.huahua.api.entity.vo.ip.IpVo;
import com.huahua.api.util.CheckUtil;
import com.huahua.api.util.CusAccessObjectUtil;
import com.huahua.api.util.IPUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

/**
 * @author LoveHuahua
 * @date 2021年09月11日 14:49
 * @description believe in yourself
 */
@RestController
@RequestMapping("/ip")
public class IpController {

    @RequestMapping("/ip2long")
    public Mono<R<IpVo>> getInfo(@RequestBody IpVo vo) {
        return Mono.fromCallable(() -> {
            String ip = vo.getIp();
            CheckUtil.checkStrNotBlank(ip, new RuntimeException("ip不能为空"));
            String address = IPUtil.getAddress(ip);
            IpVo ipVo = new IpVo();
            ipVo.setIp(ip);
            ipVo.setAddress(address);
            return R.success(ipVo);
        });
    }


    @PostMapping("/getCurrentIp")
    public Mono<R<IpVo>> getCurrentIp(ServerHttpRequest request) {
        return CusAccessObjectUtil.getIpAddressReactive(request)
                .map(ipAddress -> {
                    String address = IPUtil.getAddress(ipAddress);
                    IpVo ipVo = new IpVo();
                    ipVo.setIp(ipAddress);
                    ipVo.setAddress(address);
                    return R.success(ipVo);
                });
    }
}
